from kimi import KimiApi
from stock import stock_base_daily
from mail.send_mail import send_email
from datetime import datetime
from stock.kline_handler import analyze
from logger import logger

# 选择需要的字段
selected_fields = ['date','code', 'open', 'high', 'low', 'close', 'preclose', 'volume']


def sendAllStock(sub,stocks):
    # 使用列表推导式取第一列
    first_column = [row[0] for row in stocks]
    # 将第一列转换为逗号分隔的字符串
    result = ','.join(map(str, first_column))+ "\n"
    result += "----------------------------------"
    result += str(stocks)
    send_email(sub, result)

def kimi_init():
    kimi = KimiApi.KimiStockSession();
    if kimi.init_stock_purchase_decision():
        logger.info("ok ready!")
        return kimi
    else:
        logger.info("error ready!")
        return kimi_init()

def kimiStock(stocks):
    sub = "stock info kimi - "+datetime.now().strftime('%Y-%m-%d')
    if stocks:
        kimi = kimi_init()
        body = ""
        for __code, __date in stocks:
            body += __code + " 股票的放量日： " + __date.strftime('%Y-%m-%d') + "\n"
            logger.info("__code: "+__code)
            df = stock_base_daily.get_daily_file(__code, selected_fields=selected_fields)
            # 转换为字符串格式
            result_string = df.to_string(index=False)
            rs = kimi.chat(result_string)
            if rs.lower().startswith("error_"):
                kimi = kimi_init()
                rs = kimi.chat(result_string)
            body += rs + "\n"
            body += "------------------------------------" + "\n"
        send_email(sub, body)
    else:
        logger.info("今天没有可kimi关注的股票")
        send_email(sub, "今天没有可kimi关注的股票")



if __name__ == '__main__':
    _stocks = stock_base_daily.check_daily_all()
    sub = "stock info base - "+datetime.now().strftime('%Y-%m-%d')
    if _stocks:
        sendAllStock(sub,  _stocks)
        kimi_stock=[]
        analyze = analyze()
        for __code,__date in _stocks:
            df = stock_base_daily.get_daily_file(__code,selected_fields=selected_fields)
            if analyze.excute(__code,df):
                logger.info("股票代码：" + __code + " 加入kimi！")
                kimi_stock.append([__code,__date])
        kimiStock(kimi_stock)
    else:
        send_email(sub, "今天没有可关注的股票")
    logger.info("总体结束")


